package com.example.service.admin;

import com.example.entity.DTO.MajorDetailDTO;
import com.example.entity.Department;
import com.example.entity.Major;
import com.example.exception.CustomException;
import com.example.mapper.MajorMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MajorService {
    @Resource
    private MajorMapper majorMapper;

    public List<MajorDetailDTO> selectAllMajor(String majorName, String deptName) {
        if(majorName == null || majorName.equals("")) {
            majorName = null;
        }
        if(deptName == null || deptName.equals("")) {
            deptName = null;
        }
        return majorMapper.selectAllMajorByNameAndDeptName(majorName, deptName);
    }

    public void addMajor(Major major) {
        String name = major.getName();
        Major dbMajor = majorMapper.selectMajorByName(name);
        if(dbMajor != null) {
            throw new CustomException("500", "专业名称已存在!");
        }
        majorMapper.insert(major);
    }

    public Major selectMajor(String name) {
        return majorMapper.selectMajorByName(name);
    }

    public void updateMajor(Major major) {
        Integer id = major.getId();
        Major dbMajor = majorMapper.selectById(id);
        if(dbMajor == null) {
            throw new CustomException("500", "专业ID不存在!");
        }
        String dbName = dbMajor.getName();
        String name = major.getName();
        dbMajor = majorMapper.selectMajorByName(name);
        if(dbMajor != null && !dbName.equals(name)) {
            throw new CustomException("500", "专业名称已存在!");
        }
        majorMapper.updateById(major);
    }

    public void deleteMajor(Integer id) {
        majorMapper.deleteById(id);
    }
}
